package sort;

import java.util.Arrays;
import java.util.Comparator;

/**
 * @author Liaorun
 */
public class StudentSort {

    public static void main(String[] args) {

        Student student1 = new Student("A", 2, 20);
        Student student2 = new Student("A", 3, 21);
        Student student3 = new Student("A", 1, 22);

        Student[] students = {student1, student2, student3};

        Arrays.sort(students, new IdDescendingComparator());

        printsStudents(students);

        Arrays.sort(students, new AgeAscendingComparator());
        printsStudents(students);
    }

    private static void printsStudents(Student[] students) {
        for (Student student : students) {
            System.out.println(student.toString());
        }
    }

    static class Student {
        String name;
        int id;
        int age;

        public Student(String name, int id, int age) {
            this.name = name;
            this.id = id;
            this.age = age;
        }


        @Override
        public String toString() {
            return "Student{" + "name='" + name + '\'' + ", id=" + id + ", age=" + age + '}';
        }
    }


    /**
     * 年龄升序
     */
    public static class AgeDescendingComparator implements Comparator<Student> {

        @Override
        public int compare(Student o1, Student o2) {
            return o1.age - o2.age;
        }
    }

    /**
     * 年龄降序
     */
    public static class AgeAscendingComparator implements Comparator<Student> {

        @Override
        public int compare(Student o1, Student o2) {
            return o2.age - o1.age;
        }
    }

    /**
     * id升序
     */
    public static class IdDescendingComparator implements Comparator<Student> {

        /**
         * @param o1 the first object to be compared.
         * @param o2 the second object to be compared.
         * @return + 第一个在前， - 第二个在前面， 0 无所谓
         */
        @Override
        public int compare(Student o1, Student o2) {
            if (o1.id < o2.id) {
                return -1;
            } else if (o2.id < o1.id) {
                return 1;
            }
            return 0;
        }
    }
}
